#import "SelectionController.h"
#import "InfoControllerBase.h"

@interface SelectionController() <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray* filteredModels;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, strong) NSArray* models;
@end

@implementation SelectionController

@synthesize repository;
@synthesize filteredModels = _filteredModels;
@synthesize delegate;
@synthesize searchBar;
@synthesize infoSegueIdentifier;
@synthesize repositoryProvider;

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.models) {
        return;
    }
    
    UIBarButtonItem* rightItem = self.navigationItem.rightBarButtonItem;
    UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [spinner startAnimating];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:spinner];
    
    dispatch_queue_t queue = dispatch_queue_create("Load Models", NULL);
    dispatch_async(queue, ^() {
        NSError* error;
        self.models = [self.repository getModels:NO error:&error];
        dispatch_async(dispatch_get_main_queue(), ^(){
            [spinner stopAnimating];
            self.navigationItem.rightBarButtonItem = rightItem;
            if (error) {
                [[[UIAlertView alloc] initWithTitle:@"Erro ao Atualizar" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
                self.models = @[];
            }
            self.tableView.dataSource = self;
            [self.tableView reloadData];
        });
    });
}

-(void)setFilteredModels:(NSArray *)filteredModels {
    _filteredModels = filteredModels;
    [self.tableView reloadData];
}

-(NSArray*)filteredModels {
    if (!_filteredModels) {
        self.filteredModels = self.models;
    }
    return _filteredModels;
}

-(void)updateFilterModels {
    NSString* searchText = self.searchBar.text;
    if (!searchText || [searchText isEqualToString:@""]) {
        self.filteredModels = nil;
    } else {
        NSString* lowerSearchText = [searchText lowercaseString];
        NSMutableArray* filteredModels = [NSMutableArray array];
        for (id<SelectableModel> selectableModel in self.models) {
            if ([[selectableModel.text lowercaseString] rangeOfString:lowerSearchText].location != NSNotFound) {
                [filteredModels addObject:selectableModel];
            }
        }
        self.filteredModels = filteredModels;
    }
}

- (IBAction)updateTapped:(id)sender {
    UIBarButtonItem* rightItem = self.navigationItem.rightBarButtonItem;
    UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [spinner startAnimating];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:spinner];

    dispatch_queue_t queue = dispatch_queue_create("Update Models", NULL);
    dispatch_async(queue, ^() {
        NSError* error;
        self.models = [self.repository getModels:YES error:&error];
        dispatch_async(dispatch_get_main_queue(), ^() {
            [spinner stopAnimating];
            self.navigationItem.rightBarButtonItem = rightItem;
            if (error) {
                [[[UIAlertView alloc] initWithTitle:@"Erro ao Atualizar" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            } else {
                [self updateFilterModels];
            }
        });
    });
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self updateFilterModels];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.filteredModels.count;
}

-(id<SelectableModel>)filteredModelFor:(NSIndexPath*)indexPath {
    return [self.filteredModels objectAtIndex:indexPath.row];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    id<SelectableModel> selectableModel = [self filteredModelFor:indexPath];
    cell.textLabel.text = selectableModel.text;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate) {
        id<SelectableModel> selectableModel = [self filteredModelFor:indexPath];
        [self.delegate selectionResponse:selectableModel];
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar {
    [aSearchBar resignFirstResponder];
}

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    id<SelectableModel> model = [self filteredModelFor:indexPath];
    [self performSegueWithIdentifier:self.infoSegueIdentifier sender:model];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    InfoControllerBase* infoController = segue.destinationViewController;
    id<SelectableModel> model = sender;
    infoController.model = model;
    infoController.repositoryProvider = self.repositoryProvider;
}

@end